package com.example.lncd.ui.family;

import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.lncd.R;
import com.example.lncd.api.ApiService;
import com.example.lncd.api.RetrofitClient;
import com.example.lncd.model.GeoFence;
import com.example.lncd.model.Location;
import com.example.lncd.model.User;
import com.example.lncd.ui.auth.LoginActivity;
import com.example.lncd.util.Constants;
import com.example.lncd.util.PreferenceManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.MapView;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.model.Circle;
import com.tencent.tencentmap.mapsdk.maps.model.CircleOptions;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import android.widget.ArrayAdapter;

public class FamilyMainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private MapView mapView;
    private RecyclerView recyclerView;
    private Button btnAddRelation, btnAddGeofence;
    private FloatingActionButton fabRefresh;
    
    private TencentMap tencentMap;
    private ApiService apiService;
    private PreferenceManager preferenceManager;
    private RelatedUserAdapter adapter;
    
    private List<User> relatedUsers = new ArrayList<>();
    private Map<Long, Marker> userMarkers = new HashMap<>();
    private Map<Long, Circle> geoFenceCircles = new HashMap<>();
    
    private Long currentUserId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_family_main);
        
        // 初始化组件
        initViews();
        
        // 初始化地图
        initMap(savedInstanceState);
        
        // 初始化API和用户信息
        initApiAndUserInfo();
        
        // 加载相关用户
        loadRelatedUsers();
        
        // 设置按钮点击事件
        setButtonListeners();
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        
        // 处理Toolbar - 在使用setSupportActionBar前先检查主题中是否已有ActionBar
        try {
            setSupportActionBar(toolbar);
        } catch (IllegalStateException e) {
            // 如果已经有ActionBar，则直接设置标题
            toolbar.setTitle("家人端");
            setSupportActionBar(null); // 确保使用系统ActionBar
        }
        
        mapView = findViewById(R.id.mapView);
        recyclerView = findViewById(R.id.recyclerRelatedUsers);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        btnAddRelation = findViewById(R.id.btnAddRelation);
        btnAddGeofence = findViewById(R.id.btnAddGeofence);
        fabRefresh = findViewById(R.id.fabRefresh);
    }
    
    private void initMap(Bundle savedInstanceState) {
        // 按照腾讯地图SDK文档初始化地图
        if (mapView != null) {
            try {
                tencentMap = mapView.getMap();
                if (tencentMap != null) {
                    tencentMap.setMapType(TencentMap.MAP_TYPE_NORMAL);
                    
                    // 设置初始位置为中国中心点
                    LatLng centerOfChina = new LatLng(35.86166, 104.195397);
                    tencentMap.moveCamera(CameraUpdateFactory.newLatLngZoom(centerOfChina, 4));
                    
                    // 设置地图加载完成回调
                    tencentMap.setOnMapLoadedCallback(() -> {
                        Toast.makeText(FamilyMainActivity.this, "地图加载完成", Toast.LENGTH_SHORT).show();
                    });
                } else {
                    Toast.makeText(this, "地图初始化失败", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Toast.makeText(this, "地图初始化异常: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        } else {
            Toast.makeText(this, "地图视图未找到", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void initApiAndUserInfo() {
        apiService = RetrofitClient.getApiService();
        preferenceManager = new PreferenceManager(this);
        
        currentUserId = preferenceManager.getUserId();
        
        // 设置RecyclerView适配器
        adapter = new RelatedUserAdapter(relatedUsers, userId -> {
            // 点击关联用户时，获取并显示其位置
            getAndShowUserLocation(userId);
        });
        recyclerView.setAdapter(adapter);
    }
    
    private void loadRelatedUsers() {
        if (currentUserId == -1) {
            Toast.makeText(this, "用户信息错误，请重新登录", Toast.LENGTH_SHORT).show();
            return;
        }
        
        Call<List<User>> call = apiService.getRelatedUsers(currentUserId);
        call.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    relatedUsers.clear();
                    relatedUsers.addAll(response.body());
                    adapter.notifyDataSetChanged();
                    
                    // 加载每个用户的最新位置
                    for (User user : relatedUsers) {
                        getAndShowUserLocation(user.getId());
                    }
                    
                    // 加载地理栅栏
                    loadGeoFences();
                } else {
                    Toast.makeText(FamilyMainActivity.this, "获取关联用户失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<List<User>> call, Throwable t) {
                Toast.makeText(FamilyMainActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void getAndShowUserLocation(Long userId) {
        System.out.println("开始获取用户" + userId + "位置信息");
        Call<Location> call = apiService.getLatestLocation(userId);
        call.enqueue(new Callback<Location>() {
            @Override
            public void onResponse(Call<Location> call, Response<Location> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Location location = response.body();
                    System.out.println("成功获取位置: lat=" + location.getLatitude() + 
                                       ", lng=" + location.getLongitude() + 
                                       ", addr=" + location.getAddress());
                    showUserOnMap(userId, location);
                } else {
                    System.out.println("获取位置响应错误: " + response.code());
                    Toast.makeText(FamilyMainActivity.this, "获取位置信息失败: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Location> call, Throwable t) {
                System.out.println("获取位置网络错误: " + t.getMessage());
                Toast.makeText(FamilyMainActivity.this, "获取位置网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void showUserOnMap(Long userId, Location location) {
        try {
            // 检查地图是否初始化
            if (tencentMap == null) {
                Toast.makeText(this, "地图尚未初始化，无法显示位置", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 创建定位点
            LatLng position = new LatLng(location.getLatitude(), location.getLongitude());
            
            // 如果已有该用户的标记，则更新位置，否则创建新标记
            if (userMarkers.containsKey(userId)) {
                userMarkers.get(userId).setPosition(position);
                System.out.println("更新现有位置标记");
            } else {
                MarkerOptions markerOptions = new MarkerOptions()
                        .position(position)
                        .title("位置")
                        .snippet(location.getAddress());
                
                Marker marker = tencentMap.addMarker(markerOptions);
                userMarkers.put(userId, marker);
                System.out.println("创建新的位置标记");
            }
            
            // 移动相机到该位置
            tencentMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
            
            // 成功显示位置
            Toast.makeText(this, "已显示用户位置: " + location.getAddress(), Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            System.out.println("显示位置错误: " + e.getMessage());
            e.printStackTrace();
            Toast.makeText(this, "显示位置错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    private void loadGeoFences() {
        Call<List<GeoFence>> call = apiService.getGeoFencesByCreator(currentUserId);
        call.enqueue(new Callback<List<GeoFence>>() {
            @Override
            public void onResponse(Call<List<GeoFence>> call, Response<List<GeoFence>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    // 清除已有的地理栅栏圆圈
                    for (Circle circle : geoFenceCircles.values()) {
                        circle.remove();
                    }
                    geoFenceCircles.clear();
                    
                    // 添加新的地理栅栏圆圈
                    for (GeoFence geoFence : response.body()) {
                        if (geoFence.isActive()) {
                            showGeoFenceOnMap(geoFence);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<List<GeoFence>> call, Throwable t) {
                Toast.makeText(FamilyMainActivity.this, "获取地理栅栏失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void showGeoFenceOnMap(GeoFence geoFence) {
        // 检查地图是否初始化
        if (tencentMap == null) {
            Toast.makeText(this, "地图尚未初始化，无法显示地理栅栏", Toast.LENGTH_SHORT).show();
            return;
        }
        
        LatLng center = new LatLng(geoFence.getCenterLatitude(), geoFence.getCenterLongitude());
        
        CircleOptions circleOptions = new CircleOptions()
                .center(center)
                .radius(geoFence.getRadius())
                .fillColor(0x33FF0000)  // 半透明红色填充
                .strokeColor(0xFFFF0000) // 红色边框
                .strokeWidth(2);
        
        Circle circle = tencentMap.addCircle(circleOptions);
        geoFenceCircles.put(geoFence.getId(), circle);
    }
    
    private void setButtonListeners() {
        fabRefresh.setOnClickListener(v -> {
            loadRelatedUsers();
            Toast.makeText(this, "正在刷新位置信息...", Toast.LENGTH_SHORT).show();
        });
        
        btnAddRelation.setOnClickListener(v -> {
            showAddRelationDialog();
        });
        
        btnAddGeofence.setOnClickListener(v -> {
            showAddGeoFenceDialog();
        });
    }
    
    private void showAddRelationDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_relation, null);
        EditText etUsername = dialogView.findViewById(R.id.etUsername);
        
        new AlertDialog.Builder(this)
                .setTitle("添加关联")
                .setView(dialogView)
                .setPositiveButton("添加", (dialog, which) -> {
                    String username = etUsername.getText().toString().trim();
                    if (!username.isEmpty()) {
                        // 先查询用户ID
                        Call<List<User>> usersCall = apiService.getAllUsers();
                        usersCall.enqueue(new Callback<List<User>>() {
                            @Override
                            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                                if (response.isSuccessful() && response.body() != null) {
                                    List<User> allUsers = response.body();
                                    // 查找匹配用户名的用户
                                    for (User user : allUsers) {
                                        if (user.getUsername().equals(username)) {
                                            // 找到用户，添加关联
                                            addRelation(user.getId());
                                            return;
                                        }
                                    }
                                    Toast.makeText(FamilyMainActivity.this, "未找到该用户名的用户", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(FamilyMainActivity.this, "获取用户列表失败", Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFailure(Call<List<User>> call, Throwable t) {
                                Toast.makeText(FamilyMainActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void addRelation(Long relatedUserId) {
        // 调用添加关联API
        Call<User> call = apiService.relateUser(currentUserId, relatedUserId);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(FamilyMainActivity.this, "添加关联成功", Toast.LENGTH_SHORT).show();
                    // 刷新关联用户列表
                    loadRelatedUsers();
                } else {
                    Toast.makeText(FamilyMainActivity.this, "添加关联失败: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Toast.makeText(FamilyMainActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void showAddGeoFenceDialog() {
        if (relatedUsers.isEmpty()) {
            Toast.makeText(this, "请先添加关联用户", Toast.LENGTH_SHORT).show();
            return;
        }
        
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_geofence, null);
        
        // 初始化控件
        Spinner spinnerUser = dialogView.findViewById(R.id.spinnerUser);
        EditText etName = dialogView.findViewById(R.id.etName);
        EditText etRadius = dialogView.findViewById(R.id.etRadius);
        
        // 设置用户下拉列表
        List<String> userNames = new ArrayList<>();
        for (User user : relatedUsers) {
            userNames.add(user.getUsername());
        }
        
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
            this, android.R.layout.simple_spinner_item, userNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerUser.setAdapter(adapter);
        
        // 显示对话框
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("添加地理栅栏")
                .setView(dialogView)
                .setPositiveButton("添加", null) // 稍后设置监听器
                .setNegativeButton("取消", null)
                .create();
        
        dialog.show();
        
        // 替换默认的监听器以避免自动关闭
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
            // 验证输入
            String name = etName.getText().toString().trim();
            String radiusStr = etRadius.getText().toString().trim();
            
            if (name.isEmpty()) {
                Toast.makeText(this, "请输入栅栏名称", Toast.LENGTH_SHORT).show();
                return;
            }
            
            if (radiusStr.isEmpty()) {
                Toast.makeText(this, "请输入栅栏半径", Toast.LENGTH_SHORT).show();
                return;
            }
            
            double radius;
            try {
                radius = Double.parseDouble(radiusStr);
                if (radius <= 0) {
                    Toast.makeText(this, "半径必须大于0", Toast.LENGTH_SHORT).show();
                    return;
                }
            } catch (NumberFormatException e) {
                Toast.makeText(this, "半径格式错误", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 获取选中的用户
            int selectedPosition = spinnerUser.getSelectedItemPosition();
            if (selectedPosition < 0 || selectedPosition >= relatedUsers.size()) {
                Toast.makeText(this, "请选择用户", Toast.LENGTH_SHORT).show();
                return;
            }
            
            User selectedUser = relatedUsers.get(selectedPosition);
            
            // 提示用户在地图上选择位置
            Toast.makeText(this, "请在地图上选择中心点位置", Toast.LENGTH_LONG).show();
            
            // 设置地图点击监听器
            tencentMap.setOnMapClickListener(latLng -> {
                // 创建地理栅栏对象
                GeoFence geoFence = new GeoFence();
                geoFence.setCreatorId(currentUserId);
                geoFence.setTargetUserId(selectedUser.getId());
                geoFence.setName(name);
                geoFence.setCenterLatitude(latLng.getLatitude());
                geoFence.setCenterLongitude(latLng.getLongitude());
                geoFence.setRadius(radius);
                geoFence.setActive(true);
                
                // 调用API创建地理栅栏
                createGeoFence(geoFence);
                
                // 移除地图点击监听器
                tencentMap.setOnMapClickListener(null);
                
                // 关闭对话框
                dialog.dismiss();
            });
        });
    }

    private void createGeoFence(GeoFence geoFence) {
        Call<GeoFence> call = apiService.createGeoFence(geoFence);
        call.enqueue(new Callback<GeoFence>() {
            @Override
            public void onResponse(Call<GeoFence> call, Response<GeoFence> response) {
                if (response.isSuccessful() && response.body() != null) {
                    GeoFence createdGeoFence = response.body();
                    
                    // 在地图上显示新创建的地理栅栏
                    showGeoFenceOnMap(createdGeoFence);
                    
                    Toast.makeText(FamilyMainActivity.this, 
                        "已创建地理栅栏: " + createdGeoFence.getName(), 
                        Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(FamilyMainActivity.this, 
                        "创建地理栅栏失败: " + response.code(), 
                        Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<GeoFence> call, Throwable t) {
                Toast.makeText(FamilyMainActivity.this, 
                    "网络错误: " + t.getMessage(), 
                    Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_family_main, menu);
        
        // 确保菜单项文字显示正确
        for (int i = 0; i < menu.size(); i++) {
            MenuItem item = menu.getItem(i);
            SpannableString spanString = new SpannableString(item.getTitle().toString());
            spanString.setSpan(new ForegroundColorSpan(Color.BLACK), 0, spanString.length(), 0);
            item.setTitle(spanString);
        }
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_logout) {
            preferenceManager.clearSession();
            startActivity(LoginActivity.class);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    private void startActivity(Class<?> cls) {
        startActivity(new android.content.Intent(this, cls));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null) {
            mapView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        // MapView没有参数版本的onSaveInstanceState方法
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mapView != null) {
            mapView.onStart();
        }
    }
} 